package com.zetatech.bdp.parser.processor.impl;

import com.zetatech.bdp.entity.Field;
import com.zetatech.bdp.parser.processor.LineProcessor;
import com.zetatech.bdp.parser.utils.ScriptEnginePool;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cheng.cao@zetatech.com.cn
 */
@SuppressWarnings("all")
public class ScriptLineProcessor implements LineProcessor<Map<String, String>> {
    @Override
    public Map<String, String> processLine(File file, String line, List<Field> fields) throws IOException {
        Map<String, String> data = new HashMap<>();
        for (Field field : fields) {
            String engineName = field.getScriptEngine();
            String script = field.getScript();
            // 默认脚本引擎:groovy
            if (engineName == null || "".equalsIgnoreCase(engineName.trim())) {
                engineName = "groovy";
            }
            ScriptEngine engine = ScriptEnginePool.getEngine(engineName.toLowerCase());
            Bindings bindings = engine.createBindings();
            bindings.put("line", line);
            bindings.put("file", file.getAbsolutePath());
            try {
                String processResult = (String) engine.eval(script, bindings);
                data.put(field.getColumn(), processResult);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return data;
    }
}
